package com.sockrt;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer02 {
    public static void main(String[] args) throws IOException {
        //1.在本机的9999端口监听,等待连接
        //细节:在本机不能有其他服务监听9999端口
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端9999等待监听....");
        //2.当没有客户连接9999端口时,程序会阻塞,等待连接
        Socket scoket=serverSocket.accept();
        //3.如果有客户端连接9999端口,则会返回Socket对象
        System.out.println("服务端"+scoket.getClass());
       // InputStream inputStream=scoket.getInputStream();
        //使用字符流
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(scoket.getInputStream()));
//        int readline=0;
//        byte[] buf=new byte[1024];
//        while((readline=inputStream.read(buf))!=-1){
//            System.out.println(new String(buf,0,readline));
//        }
        String s=bufferedReader.readLine();
        System.out.println("客户端读取"+s);


        //服务端回消息
        OutputStream outputStream=scoket.getOutputStream();
        BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("I am Server nice to meet you ");
        bufferedWriter.newLine();
        bufferedWriter.flush();
        //结束输出
        scoket.shutdownOutput();

       bufferedReader.close();
       bufferedWriter.close();
        serverSocket.close();
        scoket.close();

    }
}
